import BasicConfig from "@/utils/config"
import Store from "@/store/index"
/**
 * @description 上传图片
 * @param {String} url 上传地址
 * @param {Object} formData 额外的参数对象  formData.bs: "1" 上传头像 bs:"任意值" 上传图片
 */
export const useUploadImage = async (url, formData = {}) => {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有 'original'原图, 'compressed'压缩
			sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有。如需直接开相机或直接选相册，请只使用一个选项
			success(res) {
				const file = res.tempFiles[0]
				uni.showModal({
					title: "是否上传头像?",
					success(modalRes) {
						if (modalRes.confirm) {
							BasicConfig.loadToast("上传中...")
							const token = Store.state.user.token;
							uni.uploadFile({
								url,
								filePath: file.path,
								name: 'file',
								formData: uni.$u.deepMerge({
									file: file
								}, formData),
								header: {
									Authorization: token,
									token
								},
								success: async uploadRes => {
									try {
										const response = JSON.parse(uploadRes.data)
										resolve(response)
									} catch (e) {
										resolve({
											code: 400,
											msg: "上传失败!"
										})
										BasicConfig.toast(`上传失败!`)
									}

								},
								fail: uploadErr => {
									reject(uploadErr)
									BasicConfig.toast(`上传失败![${uploadErr.errMsg}]`)
								},
								complete: uplaodCom => {
									setTimeout(() => {
										uni.hideLoading();
										uni.hideToast()
									}, 1000)
								}
							})
						}
					}
				})
			},
			fail(err) {
				console.log('图片err', err);
				// _this.$toast('获取失败!')
			}
		})

	})
}